package com.iexbuy.ihg.common;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.autoscrollview.adapter.ImagePagerAdapter;
import com.autoscrollview.widget.AutoScrollViewPager;
import com.autoscrollview.widget.indicator.CirclePageIndicator;
import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.ViewPagerAdapter;
import com.iexbuy.ihg.broadcast.DownLoadApkReceiver;
import com.iexbuy.ihg.cache.download.DownLoadThread;
import com.iexbuy.ihg.entity.AdObject;
import com.iexbuy.ihg.entity.AdObjectResponse;
import com.iexbuy.ihg.entity.AppVersion;
import com.iexbuy.ihg.entity.Shop;
import com.iexbuy.ihg.entity.ShopItemListObject;
import com.iexbuy.ihg.entity.YunItemListObject;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.ui.activity.MainTabActivity;
import com.iexbuy.ihg.ui.activity.SingleFragmentActivity;
import com.iexbuy.ihg.ui.fragment.AdWebViewFragment;
import com.iexbuy.ihg.ui.fragment.MyImagerDetailFragment;
import com.iexbuy.ihg.ui.fragment.ShopDetailFragment;
import com.iexbuy.ihg.ui.fragment.ShopItemDetailFragment;
import com.iexbuy.ihg.ui.fragment.YunGuoItemDetailFragment;
import com.iexbuy.ihg.ui.view.MyProgressDialog;
import com.iexbuy.ihg.ui.view.TwoButtonDialog;
import com.iexbuy.ihg.utils.FileUtils;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.iexbuy.ihg.utils.UnitUtils;
import com.jingchen.pulltorefresh.PullToRefreshLayout;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;


public class CommUtil {
	public static int sNotificationId = -1;
	public static boolean isDownApk = false;
	private static TwoButtonDialog sUpdateApkDialog;
	private static NotificationManager sUpdateNotificationManager;
	private static String sApkFilePath;
	private static Notification sUpdateNotification;
	private static MyProgressDialog sDownApkProgressDialog;
	private static TwoButtonDialog sConfirmDialog;

	public static void showUpdateApkDialog(final AppVersion updateInfo, final Context context) {
		final String downLoadUrl = ServiceHelper.SERVER_ROOT + updateInfo.getDownloadUrl();
		
		sUpdateApkDialog =new TwoButtonDialog(context, updateInfo, new OnClickListener() {
			@Override
			public void onClick(View v) {
					sUpdateApkDialog.dismiss();
				}
		}, new OnClickListener() {
			public void onClick(View v) {
			isDownApk = true;
			sUpdateApkDialog.dismiss();
			try {
				downloadApk(context, downLoadUrl, false);
			} catch (IOException e) {
				e.printStackTrace();
			}
		  }
		});
		sUpdateApkDialog.show();
	}

	public static void downloadApk(final Context context, final String downLoadUrl, final boolean showProgressDialog) throws IOException {
		sApkFilePath = FileUtils.getAbsPath(ExtraKeyConstant.APP_APK_DIR, ExtraKeyConstant.APP_APK_FILE_NAME);
		final Handler dowloadApkHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case DownLoadThread.START_DOWN_FILE:
					initDownLoadApk(context, showProgressDialog);
					break;
				case DownLoadThread.DWONLOAD_FLIE_COMPLETE:
					isDownApk = false;
					installApk(context, showProgressDialog);
					break;
				case DownLoadThread.DWONLOADING_FILE:
					showDownloadApkProgress(context, msg, showProgressDialog);
					break;
				case DownLoadThread.DWONLOAD_FLIE_ERROR:
					isDownApk = false;
					handleDownloadApkError(context, downLoadUrl, showProgressDialog);
					break;
				default:
					break;
				}
			}
		};
		if (downLoadUrl != null)
			App.sDownFileManager.downFile(context, downLoadUrl, ExtraKeyConstant.APP_APK_DIR, ExtraKeyConstant.APP_APK_FILE_NAME, dowloadApkHandler, true,
					false);
	}

	private static void showDownApkProgress(Context context) {
		sDownApkProgressDialog = new MyProgressDialog(context);
		sDownApkProgressDialog.setProgressStatus(context.getString(R.string.downloading_status));
		/*
		 * sDownApkProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL
		 * ); sDownApkProgressDialog.setMessage(context.getString(R.string.
		 * down_apk_progress)); sDownApkProgressDialog.setMax(100);
		 * sDownApkProgressDialog.setIndeterminate(false);
		 * sDownApkProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE,
		 * context.getString(R.string.background_donwn_apk), new
		 * DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * sDownApkProgressDialog.dismiss(); }
		 * 
		 * });
		 */
		sDownApkProgressDialog.show();
	}

	private static void initDownLoadApk(final Context context, boolean showProgressDialog) {
		if (showProgressDialog) {
			showDownApkProgress(context);
		} else {
			ToastUtils.toast(context, context.getResources().getString(R.string.background_donwn_apk_tips));
		}
		initNotifaction(context, DownLoadThread.START_DOWN_FILE);
	}

	public static void initNotifaction(final Context context, int apkId) {
		sNotificationId = apkId;
		// 初始化通知管理器
		sUpdateNotificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);
		sUpdateNotification = new Notification();
		sUpdateNotification.icon = R.drawable.ic_launcher;

		// 通知自定义视图
		sUpdateNotification.contentView = new RemoteViews(context.getPackageName(), R.layout.down_apk_notification_view);
		sUpdateNotification.contentView.setProgressBar(R.id.content_view_progress, 100, 0, false);
	}

	private static void showDownloadApkProgress(final Context context, android.os.Message msg, boolean showProgressDialog) {
		/*
		 * if (showProgressDialog) sDownApkProgressDialog.setProgress(msg.arg1);
		 */
		showNotifactionProgress(context, msg);
	}

	public static void showNotifactionProgress(final Context context, android.os.Message msg) {
		sUpdateNotification.contentView.setProgressBar(R.id.content_view_progress, 100, msg.arg1, false);
		String info = context.getString(R.string.latest_apk_downloading);
		String appName = msg.obj != null ? msg.obj.toString() : "";
		sUpdateNotification.contentView.setTextViewText(R.id.down_apk_status, appName + info + msg.arg1 + "%");
		if (msg.arg2 != 0) {
			sNotificationId = msg.arg2;
			sUpdateNotificationManager.notify(msg.arg2, sUpdateNotification);
		} else {
			sUpdateNotificationManager.notify(sNotificationId, sUpdateNotification);
		}
	};
	
	public static void cancelNotifactionProgress(int sNotificationId) {
		sUpdateNotificationManager.cancel(sNotificationId);
	}

	private static void installApk(final Context context, boolean showProgressDialog) {
		if (showProgressDialog)
			sDownApkProgressDialog.dismiss();
		startInstallApkActivity(context);
		sUpdateNotificationManager.cancel(sNotificationId);
	}

	private static void startInstallApkActivity(final Context context) {
		startInstallApkActivity(context, new File(sApkFilePath));
	}
	
	public static void startInstallApkActivity(final Context context, File file) {
		Uri uri = Uri.fromFile(file);
		Intent installIntent = new Intent(Intent.ACTION_VIEW);
		installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
		installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(installIntent);
	}

	private static void handleDownloadApkError(final Context context, final String downloadUrl, boolean showProgressDialog) {
		notifactionShowError(context, downloadUrl);
		if (showProgressDialog) {
			progressDialogShowError(context, downloadUrl);
		}
	}

//	private static JSONArray readSearchObjectFromFile(Context context) throws JSONException, IOException {
//		JSONArray existJSON = null;
//		String contentStr = FileUtils.readDataFile(context, App.AppDirConstant.APP_SEARCH_FILE_NAME);
//		if (contentStr != null) {
//			if (contentStr.length() > 0) {
//				existJSON = new JSONArray(contentStr);
//			}
//		}
//		return existJSON;
//	}

	public static void addActivity(Activity activity) {
		App.sActivityList.add(activity);
	}


	/**
	 * 
	 * @param input
	 * @return
	 */
	public static String ToDBC(String input) {
		char[] c = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == 12288) {
				c[i] = (char) 32;
				continue;
			}
			if (c[i] > 65280 && c[i] < 65375)
				c[i] = (char) (c[i] - 65248);
		}
		return new String(c);
	}

//	public static void visitWebView(Context context, String url) {
//		Intent intent = new Intent(context, SingleFragmentActivity.class);
//		intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, WebViewFragment.class);
//		BusinessMenu businessMenu = new BusinessMenu();
//		businessMenu.setServiceUrl(url);
//		businessMenu.setName("�?维�????????�????");
//		Bundle bundle = new Bundle();
//		bundle.putParcelable(ExtraKeyConstant.KEY_BUSINESS_INFO, businessMenu);
//		intent.putExtra(ExtraKeyConstant.KEY_BUNDLE, bundle);
//		intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, true);
//		context.startActivity(intent);
//	}

	public static void exit(Context context) {
		try {
			for (int i = 0; i < App.sActivityList.size(); i++) {
				if (null != App.sActivityList.get(i)) {
					App.sActivityList.get(i).finish();
				}
			}
		} catch (Exception e) {
		}
	}

	public static String getPhoneIMEI(Context mContext) {
		String imei = null;
		TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
		imei = tm.getDeviceId();
		return imei;
	}


	private static void notifactionShowError(final Context context, final String downloadUrl) {
		sUpdateNotification.flags |= Notification.FLAG_AUTO_CANCEL;
		Intent reDownloadApkIntent = new Intent(context, DownLoadApkReceiver.class);
		reDownloadApkIntent.putExtra(ExtraKeyConstant.KEY_DOWNLOAD_APK_URL, downloadUrl);
		PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, reDownloadApkIntent, 0);
		sUpdateNotification.contentView.setTextViewText(R.id.down_apk_status, context.getString(R.string.apk_download_fail));
//		sUpdateNotification.setLatestEventInfo(context, context.getString(R.string.apk_download_fail), context.getString(R.string.apk_download_fail), pendingintent); // add
		sUpdateNotificationManager.notify(sNotificationId, sUpdateNotification);
	}

	private static void progressDialogShowError(final Context context, final String downloadUrl) {
		sDownApkProgressDialog.dismiss();
	}

	/**
	 * 
	 * @param number
	 * @return
	 */
	public static boolean isMobilePhone(String number) {
		return number.matches("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
	}

	/**
	 * 
	 * @param address
	 * @return
	 */
	public static boolean isEmail(String address) {
		return address.matches("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
	}
	
	public static void showConfirmAlert(Context context, String message, final OnClickListener leftOnClickListener, final OnClickListener rightOnClickListener) {
		sConfirmDialog = new TwoButtonDialog(context, message, "确定", "取消", 
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						sConfirmDialog.dismiss();
						if (leftOnClickListener != null) leftOnClickListener.onClick(v);
					}
				}, new OnClickListener() {
					public void onClick(View v) {
						sConfirmDialog.dismiss();
						if (rightOnClickListener != null) rightOnClickListener.onClick(v);
					}
				});
		sConfirmDialog.show();
	}
	
	public static void showTwoSelectAlert(Context context, String message, String leftBtnTxt, String rightBtnTxt, final OnClickListener leftOnClickListener, final OnClickListener rightOnClickListener) {
		sConfirmDialog = new TwoButtonDialog(context, message, leftBtnTxt, rightBtnTxt, 
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						sConfirmDialog.dismiss();
						leftOnClickListener.onClick(v);
					}
				}, new OnClickListener() {
					public void onClick(View v) {
						sConfirmDialog.dismiss();
						rightOnClickListener.onClick(v);
					}
				});
		sConfirmDialog.show();
	}
	
	public static void showAlert(Context context, CharSequence title, CharSequence message, final DialogInterface.OnClickListener listener) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		final AlertDialog alert = builder.create();

		alert.show();
		Window view = alert.getWindow();
		view.setContentView(R.layout.return_alert_button_dialog);
		LayoutInflater flater = LayoutInflater.from(context);
		// View view = flater.inflate(R.layout.return_alert_button_dialog,
		// null);
		Button btnreturn = (Button) view.findViewById(R.id.cancle);// 注：“View.”别忘了，不然则找不到资源
		btnreturn.setText(R.string.confirm);
		
		TextView tv_title = (TextView) view.findViewById(R.id.dialog_title);
		View tv_title_view = (View) view.findViewById(R.id.dialog_titl_view);
		if (title != null && !TextUtils.isEmpty(title)) {
			tv_title.setText(title);
			tv_title.setVisibility(View.VISIBLE);
			tv_title_view.setVisibility(View.VISIBLE);
		} else {
			tv_title.setVisibility(View.GONE);
			tv_title_view.setVisibility(View.GONE);
		}
		TextView tv_msg = (TextView) view.findViewById(R.id.dialog_message);
		tv_msg.setText(message);
		// builder.setView(view);
		btnreturn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alert.dismiss();
				if (listener != null)
					listener.onClick(alert, 0);
			}
		});

		// new
		// AlertDialog.Builder(context).setTitle(title).setMessage(message).setPositiveButton(R.string.Return,
		// listener).show();
	}

	/**
	 * 
	 * @param adapter
	 * @param listView
	 */
	public static void expandListView(BaseAdapter adapter, ListView listView) {
		int totalHeight = 0;
		for (int i = 0, len = adapter.getCount(); i < len; i++) { // listAdapter.getCount()
			View listItem = adapter.getView(i, null, listView);
			listItem.measure(0, 0); // 
			totalHeight += listItem.getMeasuredHeight(); // 
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1)) + listView.getPaddingTop() + listView.getPaddingBottom();
		listView.setLayoutParams(params);
	}

	/**
	 * 
	 * @param context
	 * @param enabled
	 */
	public static void setMobileDataStatus(Context context, boolean enabled) {
		ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		// ConnectivityManager
		Class<?> conMgrClass = null;
		// ConnectivityManager
		Field iConMgrField = null;
		// IConnectivityManager
		Object iConMgr = null;
		// IConnectivityManager
		Class<?> iConMgrClass = null;
		// setMobileDataEnabled
		Method setMobileDataEnabledMethod = null;
		try {
			conMgrClass = Class.forName(conMgr.getClass().getName());
			iConMgrField = conMgrClass.getDeclaredField("mService");
			iConMgrField.setAccessible(true);
			iConMgr = iConMgrField.get(conMgr);
			iConMgrClass = Class.forName(iConMgr.getClass().getName());

			setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);

			setMobileDataEnabledMethod.setAccessible(true);
			setMobileDataEnabledMethod.invoke(iConMgr, enabled);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param context
	 * @param getMobileDataEnabled
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static boolean getMobileDataStatus(Context context, String getMobileDataEnabled) {
		ConnectivityManager cm;
		cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		Class cmClass = cm.getClass();
		Class[] argClasses = null;
		Object[] argObject = null;
		Boolean isOpen = false;
		try {
			Method method = cmClass.getMethod(getMobileDataEnabled, argClasses);
			isOpen = (Boolean) method.invoke(cm, argObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isOpen;
	}

	/**
	 * @param radiogroup
	 * @return 
	 */
	public static int getCheckedPositionInRadioGroup(RadioGroup radiogroup) {
		int id = radiogroup.getCheckedRadioButtonId();
		if (id != -1)
			return radiogroup.indexOfChild(radiogroup.findViewById(id));
		return -1;
	}

	/**
	 * 
	 * @param str
	 * @return
	 */
	public static String wipeOffUnDigitChar(String str) {
		if (TextUtils.isEmpty(str))
			return null;

		StringBuffer sb = new StringBuffer(str.length());
		for (int i = 0; i < str.length(); ++i) {
			char c = str.charAt(i);
			if ((c >= '0' && c <= '9') || c == '-' || c == '.')
				sb.append(c);
		}
		return sb.toString();
	}

	public static float parse2Float(String str) {
		float result = 0;
		String temp = wipeOffUnDigitChar(str);

		if (!TextUtils.isEmpty(temp))
			temp = wipeOffUnDigitChar(temp);
		if (!TextUtils.isEmpty(temp))
			result = Float.parseFloat(temp);

		return result;
	}

	public static double parse2Double(String str) {
		double result = 0;
		String temp = wipeOffUnDigitChar(str);

		if (!TextUtils.isEmpty(temp))
			temp = wipeOffUnDigitChar(temp);
		if (!TextUtils.isEmpty(temp))
			result = Double.parseDouble(temp);

		return result;
	}

	/**
	 * 
	 * @param str
	 * @param defaultInt
	 * @return
	 */
	public static int parse2Integer(String str, int defaultInt) {
		try {
			defaultInt = Integer.parseInt(str);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return defaultInt;
	}

	/**
	 * 
	 * @param pastNum
	 * @return 
	 */
	public static String getMonthPast(int pastNum) {
		return getMonthPast("%04d%02d", pastNum);
	}

	/**
	 * @param format
	 * @param pastNum
	 * @return 
	 */
	public static String getMonthPast(String format, int pastNum) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());

		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);

		month -= pastNum;
		if (month < 0) {
			year--;
			month += 12;
		}

		return String.format(format, year, month + 1);
	}

	/**
	 * @param str
	 * @return 
	 */
	public static boolean isContainChinese(String str) {

		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		Pattern p = Pattern.compile("^[0-9]*$");
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		}
		return false;
	}

	/**
	 * 
	 * @param number
	 * @return
	 */
	public static final String removeNoNecessaryWordsFromPhoneNumber(String number) {
		if (number.startsWith("+86"))
			number = number.substring(3);
		if (number.indexOf('-') != -1) {
			StringBuilder sb = new StringBuilder();
			char[] chars = number.toCharArray();
			for (char c : chars)
				if (c != '-')
					sb.append(c);

			number = sb.toString();
		}
		return number;
	}
	
	public static void openSingleFragmentActivity(Context context, Class fragementClss) {
		Intent intent = new Intent(context, SingleFragmentActivity.class);
		intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, fragementClss);
		intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, true);
		context.startActivity(intent);
	}

	//初始广告图片
	public static void initAdListData(final Context context, final String adType, final ViewPager displayLayoutView) {
		final List<AdObject> adObjects = new ArrayList<AdObject>();
		//滚动图片
		final List<View> adItemViews = new ArrayList<View>();
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("type", adType);
		ServiceHelper.send(context, ServiceHelper.GET_ADS_BANNERS, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						AdObjectResponse response = JsonUtils.parseJsonStrToObject(responseInfo.result, AdObjectResponse.class);
						adObjects.clear();
						adObjects.addAll(response.getBody());

						if (displayLayoutView == null) return;
						//初始化引导图片列表
						LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
						displayLayoutView.removeAllViews();
						adItemViews.clear();
						for (final AdObject ad : adObjects) {
							ImageView iv = new ImageView(context);
							iv.setLayoutParams(mParams);
							iv.setScaleType(ImageView.ScaleType.FIT_XY);
							App.bitmapUtils.display(iv, ad.getUrl());
							iv.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View view) {
									CommUtil.handleAdViewClick(context, ad);
								}
							});
							adItemViews.add(iv);
						}
						ViewPagerAdapter vpAdapter = new ViewPagerAdapter(adItemViews);
						displayLayoutView.setAdapter(vpAdapter);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	//初始广告图片
	public static void initAdListData(final Context context, final String adType, final RelativeLayout displayLayoutView) {
		final List<AdObject> adObjects = new ArrayList<AdObject>();
		//滚动图片
		final View bannerView = LayoutInflater.from(context).inflate(R.layout.banner_view, null);
		final AutoScrollViewPager viewPager = (AutoScrollViewPager) bannerView.findViewById(R.id.view_pager);
		final CirclePageIndicator indicator = (CirclePageIndicator) bannerView.findViewById(R.id.indicator);

		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("type", adType);
		ServiceHelper.send(context, ServiceHelper.GET_ADS_BANNERS, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
					}

					@Override
					public void onCancelled() {
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						AdObjectResponse response = JsonUtils.parseJsonStrToObject(responseInfo.result, AdObjectResponse.class);
						List<AdObject> adObjects = response.getBody();
						if (displayLayoutView == null) return;
						List<String> imgUrls = new ArrayList<String>();
						List<OnClickListener> onClickListeners = new ArrayList<OnClickListener>();
						for (final AdObject ad : adObjects) {
							imgUrls.add(ad.getUrl());
							onClickListeners.add(new OnClickListener() {
								@Override
								public void onClick(View view) {
									CommUtil.handleAdViewClick(context, ad);
								}
							});
						}
						viewPager.setAdapter(new ImagePagerAdapter(context, imgUrls, onClickListeners));
						indicator.setViewPager(viewPager);
						viewPager.setInterval(5000);
						viewPager.setSlideBorderMode(AutoScrollViewPager.SLIDE_BORDER_MODE_NONE);
						viewPager.setCycle(true);
						viewPager.startAutoScroll();

						displayLayoutView.addView(bannerView);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
					}
				});
	}

	//初始广告图片
	public static void initScrollViewPages(final Context context, RelativeLayout displayLayoutView, List<String> imgUrls, List<OnClickListener> onClickListeners) {
		final List<AdObject> adObjects = new ArrayList<AdObject>();
		//滚动图片
		final View bannerView = LayoutInflater.from(context).inflate(R.layout.banner_view, null);
		final AutoScrollViewPager viewPager = (AutoScrollViewPager) bannerView.findViewById(R.id.view_pager);
		final CirclePageIndicator indicator = (CirclePageIndicator) bannerView.findViewById(R.id.indicator);
		onClickListeners = new ArrayList<OnClickListener>();
		for(final String url: imgUrls){
			final List<String> urls = imgUrls;
			onClickListeners.add(new OnClickListener() {
				@Override
				public void onClick(View view) {
					CommUtil.handlerOpenImgView(context, url, urls);
				}
			});

		}
		viewPager.setAdapter(new ImagePagerAdapter(context, imgUrls, onClickListeners, ImageView.ScaleType.FIT_CENTER));

		indicator.setViewPager(viewPager);
		viewPager.setInterval(5000);
		viewPager.setSlideBorderMode(AutoScrollViewPager.SLIDE_BORDER_MODE_NONE);
		viewPager.setCycle(true);
		viewPager.startAutoScroll();

		displayLayoutView.addView(bannerView);
	}

	public static TextView createSingleLineTextView(Context context, String text) {
		TextView textView = new TextView(context);
		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		textView.setPadding(0, 8, 0, 0);
		textView.setText(text);
		return textView;
	}

	public static String getStatusNameFromCode(String statusCode) {
		String statusStr = "未知状态";
		try{
			switch (Integer.valueOf(statusCode)) {
				case 1:
					statusStr = "待支付";
					break;
				case 2:
					statusStr = "已支付";
					break;
				case 3:
					statusStr = "已发货";
					break;
				case 4:
					statusStr = "已完成";
					break;
				case 5:
					statusStr = "已取消";
					break;
			}
		} catch (Exception e) {}

		return statusStr;
	}

	public static String getLongitude() {
		if (StringUtil.isEmpty(App.sPreferences.getLongitude())) {
			return "113.275995";
		} else {
			return App.sPreferences.getLongitude();
		}
	}

	public static String getLatitude() {
		if (StringUtil.isEmpty(App.sPreferences.getLatitude())) {
			return "23.117055";
		} else {
			return App.sPreferences.getLatitude();
		}
	}

	public static void handleAdViewClick(Context context, AdObject adObject) {
		if ("2".equalsIgnoreCase(adObject.getJumpType())) {
			return;
		} else if ("1".equalsIgnoreCase(adObject.getJumpType())) {
			//原生页面
			if ("Main_xf".equalsIgnoreCase(adObject.getJumpPageTag())) {//消费页面
				MainTabActivity.getInstance().setCurrentTab(0);
			} else if ("Main_sc".equalsIgnoreCase(adObject.getJumpPageTag())) {//换购页面
				MainTabActivity.getInstance().setCurrentTab(1);
			} else if ("Main_0g".equalsIgnoreCase(adObject.getJumpPageTag())) {//0购页面
				MainTabActivity.getInstance().setCurrentTab(2);
			} else if ("Main_md".equalsIgnoreCase(adObject.getJumpPageTag())) {//免单页面
				MainTabActivity.getInstance().setCurrentTab(3);
			} else if ("Main_wd".equalsIgnoreCase(adObject.getJumpPageTag())) {//我的页面
				MainTabActivity.getInstance().setCurrentTab(4);
			} else if ("Detail_sh".equalsIgnoreCase(adObject.getJumpPageTag())) {//店铺详情页面
				Shop shop = new Shop();
				shop.setId(adObject.getJumpData1());
				ShopDetailFragment.setShop(shop);
				CommUtil.openSingleFragmentActivity(context, ShopDetailFragment.class);
			} else if ("Detail_sh_sp".equalsIgnoreCase(adObject.getJumpPageTag())) {//店铺商品详情页面
				ShopItemListObject shopItemListObject = new ShopItemListObject();
				shopItemListObject.setItemId(adObject.getJumpData1());
				ShopItemDetailFragment.setShopItemListObject(shopItemListObject);
				CommUtil.openSingleFragmentActivity(context, ShopItemDetailFragment.class);
			} else if ("Detail_sc_sp".equalsIgnoreCase(adObject.getJumpPageTag())) {//商城商品页面，与商家商品页面相同

			} else if ("Detail_0g_sp".equalsIgnoreCase(adObject.getJumpPageTag())) {//0购详情页面
				YunItemListObject yunItemListObject = new YunItemListObject();
				yunItemListObject.setItemId(adObject.getJumpData1());
				YunGuoItemDetailFragment.setYunItemListObject(yunItemListObject);
				CommUtil.openSingleFragmentActivity(context, YunGuoItemDetailFragment.class);
			}
		} else if ("0".equalsIgnoreCase(adObject.getJumpType())) {
			//webview详情
			AdWebViewFragment.setAdObject(adObject);
			CommUtil.openSingleFragmentActivity(context, AdWebViewFragment.class);
		}
	}
	public static void handlerOpenImgView(Context context,String url,List<String> urls){
		MyImagerDetailFragment.setUrls(urls);
		MyImagerDetailFragment.setUrl(url);
		CommUtil.openSingleFragmentActivity(context, MyImagerDetailFragment.class);

	}

	public static String formatDistance(String distance) {
		String returnStr = distance+ "米";
		if (new BigDecimal(distance).compareTo(new BigDecimal("1000")) > 0) {
			returnStr = new BigDecimal(distance).divide(new BigDecimal("1000"), 1, RoundingMode.DOWN).setScale(1, RoundingMode.DOWN).toString() + "公里";
		} else {
			returnStr = new BigDecimal(distance).setScale(0, BigDecimal.ROUND_DOWN).toString() + "米";
		}
		return returnStr;
	}

	public static int calculatCoinFromCash(String cash, String shopRate) {
		int goldCoin = 0;
		if (StringUtil.isNotEmpty(cash) && StringUtil.isNotEmpty(shopRate)) {
			goldCoin = new BigDecimal(cash).multiply(new BigDecimal(shopRate)).multiply(BigDecimal.TEN).multiply(new BigDecimal("0.5")).divide(new BigDecimal("100")).intValue();
			Log.d("CommUtil", "cash:"+cash+", shopRate:"+shopRate + ", goldcoin:"+goldCoin);
		}
		return goldCoin;
	}

	public static void loadWebviewData(WebView webview, String data) {
		if (webview == null || StringUtil.isEmpty(data)) return;

		webview.getSettings().setDefaultTextEncodingName("UTF-8");
		webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		webview.getSettings().setUseWideViewPort(true);
		webview.getSettings().setLoadWithOverviewMode(true);
		if (!data.contains("<html")) {
			data = "<html><head><meta name=\"viewport\" content=\"width=device-width,user-scalable=no\" /></head><body style=\"word-break:break-all\">" + data + "</body></html>";
		}
		webview.loadData(data, "text/html; charset=UTF-8", null);
	}
}
